# coding=utf-8
import json
import random
import time
from worldcup.apps.userModel.models import LotteryCode
from worldcup.commons.CommonResult import rest, CommonResult


@rest
def lottery(request):
	'''
	dt = "2018-04-03 20:28:54"
	timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
	timestamp = time.mktime(timeArray)
'''
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	user_openid = reqest_params.get('openid')

	try:
		user = LotteryCode.objects.get(openid=user_openid)
		return CommonResult(-1, "您已经提交过比分，不能重复提交！")
	except LotteryCode.DoesNotExist:
		user = LotteryCode.objects.create(openid=user_openid, activity=reqest_params.get("score"))
		flag =True
		while(flag):
			code = random.randint(100,999)
			if LotteryCode.objects.filter(code=('6dong'+str(code))).count()>=1:#如果已经存在该号码
				pass
			else:
				user.code = '6dong'+str(code)
				user.num = 1
				user.save()
				flag=False

		result = {
			'code':user.code
		}
		return CommonResult(0,result)


